package com.threefish.modules.report.provider;

import com.bstek.ureport.exception.ReportComputeException;
import com.bstek.ureport.provider.image.ImageProvider;
import com.threefish.modules.report.entity.AnnexDO;
import com.threefish.modules.report.service.AnnexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;

/**
 * @author 黄川 huchuc@vip.qq.com
 * @date: 2018/9/6
 */
@Component
public class DBImageProvider implements ImageProvider {


    @Autowired
    AnnexService annexService;

    @Value("${annex.parentPath}")
    String annexParentPath;

    @Override
    public InputStream getImage(String id) {
        try {
            AnnexDO annex = annexService.fetch(id);
            File file = Paths.get(annexParentPath, annex.getSavedPath()).toFile();
            if (file.exists()) {
                return new FileInputStream(file);
            }
            throw new ReportComputeException("图片已经不存在了");
        } catch (IOException e) {
            throw new ReportComputeException(e);
        }
    }

    @Override
    public boolean support(String id) {
        return true;
    }

}
